<template>
  <view :class="{overflow: show}">
    <view class="demo" :style="'height:' + demo.height + 'px;' + 'padding-top:' + demo.top + 'px;padding-bottom:10rpx'">
      <view @click="back" class="left" :style="'top:' + demo.top + 'px'">
        <image class="fanhuiIcon" src="/static/icon/fanhui.png" mode="" />
      </view>
      商品详情
    </view>
    <view class="swiperBox c-relative">
      <u-swiper :list="list" class="a"></u-swiper>
      <image class="c-absolute right30 top30" @click="collect" :src="iconSrc" mode="" />
    </view>
    <u-card :border="true" :show-foot="false" :show-head="false">
      <view slot="body" class="contbody">
        <view class="c-color-000 c-mt30">{{ goods.name }}</view>
        <view class="c-mt30 c-flex c-flex-between">
          <view class="c-flex">
            <view class="c-color money c-fw600">
              <text class="a">￥</text>
              <text class="p">
                {{ price }}
              </text>
              <text class="j"
                >价格 ￥<text class="line">{{ goods.originalPrice }}</text></text
              >
            </view>
          </view>
          <view class="c-flex c-ml15">
            <NumberAdd @change="changeNum" :val="num" numColor="#F3651F" btnType="circle" />
          </view>
        </view>
      </view>
    </u-card>
    <u-line color="#f4f4f4"></u-line>
    <cell left="规格" center="选择规格" :right="right" @open="open"></cell>
    <view v-show="right === 'arrow-down'" class="c-p15">
      <view class="specification c-flex">
        <u-button
          v-for="(item, index) in goods.skuList"
          :key="item.id"
          :hair-line="false"
          :custom-style="activeNum === index ? activeBtnStyle : formerBtnStyle"
          @click="changeActive(index, item.id, item.price)"
          >{{ item.name }}</u-button
        >
      </view>
    </view>
    <cell left="服务" center="付款后15天内发货，不支持7天..." :right="'arrow-right'"></cell>
    <!-- <cell left="优惠券" center="请选择优惠券" :right="'arrow-right'"></cell> -->
    <cell left="快递" center="快递包邮"></cell>
    <u-line color="#f4f4f4"></u-line>
    <view class="c-p15">
      <view class="fenText">当前商品可进行分销，点击一键分销，成功售出后您将获得{{ goods.brokerage }}元</view>
    </view>
    <u-line color="#f4f4f4"></u-line>
    <view class="c-p15 mb90">
      <h4>商品详情</h4>
      <view class="c-color-ccc c-mt10 c-fs0" v-html="goods.description"> </view>
    </view>
    <view class="buttonBox">
      <u-button
        shape="circle"
        :hair-line="false"
        :custom-style="{
          background: 'linear-gradient(80deg, #FF63A4, #FF8861)',
          boxShadow: '0px 15px 50px 0px rgba(255, 105, 153, 0.41)',
          color: '#fff',
          border: 'none',
          width: '230rpx'
        }"
        hover-class="none"
        @click="add"
        >加入购物车</u-button
      >
      <u-button
        shape="circle"
        :hair-line="false"
        :custom-style="{
          background: 'linear-gradient(80deg, #FFB245, #FF814A)',
          boxShadow: '0px 15px 50px 0px rgba(255, 128, 53, 0.41)',
          color: '#fff',
          border: 'none',
          width: '228rpx'
        }"
        hover-class="none"
        @click="commitOrder"
        >提交订单</u-button
      >
      <view class="fenxiao" @click="fenxiao">
        <view class="qian">可获得{{ goods.brokerage }}元</view>
        <view class="fenxiaozi">一键分销</view>
      </view>
    </view>
    <u-popup v-model="show" mode="bottom" border-radius="40">
      <view class="c-flex c-flex-between share">
        <button open-type="share">
          <image src="/static/icon/weixin.png" mode="" />
          <view>分享好友</view>
        </button>
        <button @click="exportImg">
          <image src="/static/icon/xiangce.png" mode="" />
          <view>保存至相册</view>
        </button>
      </view>
      <u-line color="#eee"></u-line>
      <view class="quxiao" @click="show = false"> 取消 </view>
    </u-popup>
    <view v-if="show" class="canvas">
      <view class="canvasBox">
        <canvas :style="{width: canvasW + 'px', height: canvasH + 'px'}" canvas-id="myCanvas" id="myCanvas"></canvas>
      </view>
    </view>
  </view>
</template>

<script>
  // import NavBar from '@/commponents/public/navbar'
  import cell from '@/commponents/public/cell/cell'
  import NumberAdd from '@/commponents/public/numberAdd'
  import url from '@/common/util/url'
  import goods from '@/services/goods'
  import shoppingCar from '@/services/shoppingCar'
  import collect from '@/services/collect'

  export default {
    components: {
      // NavBar,
      cell,
      NumberAdd
    },
    data() {
      return {
        demo: {
          top: 0,
          height: 0
        },
        price: '',
        canvasW: 0, // 画布宽
        canvasH: 0, // 画布高
        SystemInfo: {}, // 设备信息
        goodsImg: {}, // 商品主图
        ewmImg: {}, // 二维码图片
        ewmW: 120, // 二维码大小
        title: '', // 商品标题
        Oldprice: '350.00', // 原价
        activeBtnStyle: {
          background: '#FFF0E8',
          color: '#FF6A21',
          border: 'none',
          padding: '0 44rpx',
          fontSize: '26rpx',
          marginRight: '20rpx',
          borderRadius: '80px',
          height: '70rpx'
        },
        formerBtnStyle: {
          background: '#EFEFEF',
          color: '#B8B8B8',
          border: 'none',
          padding: '0 15rpx',
          fontSize: '26rpx',
          marginRight: '20rpx',
          borderRadius: '80px',
          height: '70rpx'
        },
        titleStyle: {
          color: '#000',
          fontSize: '33rpx',
          fontWeight: '600'
        },
        start: '',
        list: [],
        goods: {},
        activeNum: 0,
        num: 1,
        sku: '',
        params: '',
        iconSrc: '',
        right: 'arrow-right',
        show: false,
        scene: '',
        share: false
      }
    },

    onLoad(options) {
      // 扫码进入小程序
      if (options.scene) {
        this.scene = decodeURIComponent(options.scene)
        // '/'是我们定义的参数链接方式
        let userId = this.scene.split(';')[0].split('=')[1]
        let goodsId = this.scene.split(';')[1].split('=')[1]
        uni.setStorageSync('shareUserId', userId)
        this.params = new Object()
        this.params.id = parseInt(goodsId)
        this.getDetail()
      }
      if (options.goodsId) {
        this.share = true
        uni.setStorageSync('shareUserId', options.userId)

        this.params = new Object()
        this.params.id = parseInt(options.goodsId)
        this.getDetail()
      }
    },

    // // 用户点击右上角分享朋友圈
    // onShareTimeline: function () {
    //   return {
    //     // titile就是分享名称  query为分享进入链接，imageurl就是图片相对获取就可以
    //     title: '我发现了一个好东西，快来看看吧~',
    //     query: {
    //       key: '/pages/productDetails/index?goodsId=' + this.params.id + ';userId=' + uni.getStorageSync('userId')
    //     }
    //   }
    // },
    created() {
      const demo = uni.getMenuButtonBoundingClientRect()
      this.demo.top = demo.top
      this.demo.height = demo.height
    },
    onShow() {
      uni.setStorageSync('quan', [])
      uni.setStorageSync('quanchangquan', [])
    },
    mounted() {
      if (!(this.scene || this.share)) {
        this.params = url.getCurrentPageParam()
        this.getDetail()
      }
    },
    onShareAppMessage(res) {
      return {
        title: '我发现了一个好东西，快来看看吧~',
        path: '/pages/productDetails/index?goodsId=' + this.params.id + '&userId=' + uni.getStorageSync('userId') // 分享的页面路径
      }
    },
    methods: {
      dtod(url) {
        return new Promise(resolve => {
          uni.compressImage({
            src: url,
            quality: 100,
            success: res => {
              resolve(res.tempFilePath)
            }
          })
        })
      },
      getQueryParams(queryString) {
        // 微信扫码得到的内容进行了一次编码，所以官方要求需要进行decodeURIComponent一次
        queryString = decodeURIComponent(queryString)
        let params = {}
        if (queryString) {
          let queryArray = queryString.split('?')
          if (queryArray.length > 1) {
            let query = queryArray[1]
            let array = query.split('&')
            array.map(value => {
              let valueArray = value.split('=')
              if (valueArray.length > 1) {
                // 还需要对value进行解码（可能涉及到在value为中文字符，在赋值到二维码前进行了encodeURI编码）
                Object.assign(params, {[valueArray[0]]: decodeURI(valueArray[1])})
              }
            })
          }
        }
        return params
      },
      back() {
        uni.navigateBack({
          delta: 1
        })
      },
      canvasIdErrorCallback: function (e) {
        console.error(e.detail.errMsg)
      },
      // 获取图片信息
      getImageInfo(image) {
        return new Promise((resolve, reject) => {
          wx.getImageInfo({
            src: image,
            success: function (res) {
              console.log('解析成功', image)
              resolve(res)
            },
            fail: function (err) {
              console.log('解析失败', image)
              console.log(err)
            }
          })
        })
      },

      // 获取设备信息
      getSystemInfo() {
        return new Promise((resolve, reject) => {
          uni.getSystemInfo({
            success: function (res) {
              resolve(res)
            }
          })
        })
      },

      fenxiao() {
        this.draw()
      },
      open() {
        if (this.right === 'arrow-right') {
          this.right = 'arrow-down'
        } else {
          this.right = 'arrow-right'
        }
      },
      exportImg() {
        uni.canvasToTempFilePath({
          fileType: 'jpg',
          canvasId: 'myCanvas',
          success: function (res) {
            // 在H5平台下，tempFilePath 为 base64
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: function () {
                uni.showToast({
                  icon: 'none',
                  position: 'bottom',
                  title: '保存成功' // res.tempFilePath
                })
              }
            })
          }
        })
      },
      collect() {
        if (this.isCollect) {
          this.collectDel()
        } else {
          this.collectAdd()
        }
      },
      collectAdd() {
        collect.add(this.params.id).then(() => {
          this.isCollect = 1
          this.iconSrc = '/static/icon/aixin_true.png'
          wx.showToast({
            title: '收藏成功',
            duration: 2000
          })
        })
      },
      collectDel() {
        collect.del([this.params.id]).then(() => {
          this.isCollect = 0
          this.iconSrc = '/static/icon/aixin.png'
          wx.showToast({
            title: '取消收藏成功',
            duration: 2000
          })
        })
      },
      changeNum(num) {
        this.num = num
      },
      getDetail() {
        goods
          .detail({
            id: this.params.id,
            userId: uni.getStorageSync('userId')
          })
          .then(data => {
            let list = data.albumPics.split(',')
            list.forEach((element, index) => {
              list[index] = {
                image: element
              }
            })
            this.list = list
            this.goods = data
            this.isCollect = this.goods.isCollect
            this.price = this.goods.skuList[0].price
            this.title = this.goods.name
            this.iconSrc = this.isCollect ? '/static/icon/aixin_true.png' : '/static/icon/aixin.png'
          })
      },
      async draw() {
        let code
        code = await goods.getCode({
          page: 'pages/productDetails/index',
          scene: `userId=${uni.getStorageSync('userId')};goodsId=${this.goods.id}`
        })

        // 获取设备信息，主要获取宽度，赋值给canvasW 也就是宽度：100%
        this.SystemInfo = await this.getSystemInfo()
        // let a = await this.dtod(this.goods.pic)
        // 获取商品主图，二维码信息，APP端会返回图片的本地路径（H5端只能返回原路径）
        // this.goods.pic +
        // let goodsImg = await this.getImageInfo('https://ailiya.oss-cn-beijing.aliyuncs.com/20210724/99265673ef28485982fec512ac87fe98.png')
        let goodsImg = await this.getImageInfo(this.goods.pic)
        console.log(1)
        this.code = await this.getImageInfo(code)
        console.log(2)

        this.canvasW = this.SystemInfo.windowWidth * 0.9 // 画布宽度

        this.canvasH = 490 // 画布高度 = 主图高度+二维码高度 + 文字图片的间距（大概50）

        // 如果主图，二维码图片，设备信息都获取成功，开始绘制海报，这里需要用setTimeout延时绘制，否则可能会出现图片不显示。
        if (
          goodsImg.errMsg == 'getImageInfo:ok' &&
          this.code.errMsg == 'getImageInfo:ok' &&
          this.SystemInfo.errMsg == 'getSystemInfo:ok'
        ) {
          uni.showToast({
            icon: 'loading',
            mask: true,
            duration: 13000,
            title: '海报绘制中,请稍后'
          })
          this.show = true

          setTimeout(() => {
            let ctx = uni.createCanvasContext('myCanvas', this)
            // 填充背景色，白色
            ctx.setFillStyle('#fff') // 默认白色
            ctx.fillRect(0, 0, this.canvasW, this.canvasH) // fillRect(x,y,宽度，高度)

            this.drawCircular(ctx, goodsImg.path, 20, 20, this.canvasW - 40, this.canvasW - 40)
            // 绘制商品主图，二维码
            ctx.drawImage(this.code.path, this.canvasW - 20 - 80, this.canvasW + 40, 70, 70) // drawImage(图片路径,x,y,绘制图像的宽度，绘制图像的高度)

            // 3、绘制商品标题，多余文字自动换行
            ctx.setFontSize(16) // setFontSize() 设置字体字号
            ctx.font = `normal bold 16px Arial,sans-serif`
            ctx.setFillStyle('#2D2D2D') // setFillStyle() 设置字体颜色

            /* str 这段代码是我百度找的，参考别人的。canvas不能自动换行，需要自行计算 */
            let _strlineW = 0
            let _strLastIndex = 0 // 每次开始截取的字符串的索引
            let _strHeight = this.canvasW + 10 // 绘制字体距离canvas顶部的初始高度
            let _num = 1
            for (let i = 0; i < this.title.length; i++) {
              _strlineW += ctx.measureText(this.title[i]).width
              if (_strlineW > this.canvasW - 40) {
                if (_num == 2 && 2) {
                  // 文字换行数量大于二进行省略号处理
                  ctx.fillText(this.title.substring(_strLastIndex, i - 5) + '...', 20, _strHeight)
                  _strlineW = 0
                  _strLastIndex = i
                  _num++
                  break
                } else {
                  ctx.fillText(this.title.substring(_strLastIndex, i), 20, _strHeight)
                  _strlineW = 0
                  _strHeight += 20
                  _strLastIndex = i
                  _num++
                }
              } else if (i == this.title.length - 1) {
                ctx.fillText(this.title.substring(_strLastIndex, i + 1), 20, _strHeight)
                _strlineW = 0
              }
            }

            /* end */

            // 4、商品价格
            ctx.setFontSize(16) // 字号
            ctx.setFillStyle('#FF6A21') // 颜色
            ctx.fillText('￥' + this.price, 20, this.canvasW + 62) // （文字，x，y）

            // 5、邀请信息

            this.drawRoundedRect(ctx, '#fff', '#FFF0E8', 20, this.canvasW + 75, 200, 30, 15)

            ctx.setFontSize(12)
            ctx.setFillStyle('#FF6A21')
            ctx.fillText('长按扫描识别二维码', 35, this.canvasW + 95)

            ctx.draw(true, ret => {
              // draw方法 把以上内容画到 canvas 中。
              uni.showToast({
                icon: 'success',
                mask: true,
                title: '绘制完成'
              })
            })
          }, 1500)
        } else {
          console.log('err')
        }
      },
      drawCircular(ctx, url, x, y, width, height) {
        // 画圆形头像
        let avatarurl_width = width
        let avatarurl_heigth = height
        let avatarurl_x = x
        let avatarurl_y = y
        ctx.save()
        ctx.beginPath()
        this.drawRoundedRect(ctx, '#fff', '#fff', x, y, width, height, 10)
        ctx.clip()
        ctx.drawImage(url, avatarurl_x, avatarurl_y, avatarurl_width, avatarurl_heigth)
        ctx.restore()
      },
      roundedRect(ctx, x, y, width, height, radius) {
        if (width <= 0 || height <= 0) {
          ctx.arc(x, y, radius, 0, Math.PI * 2)
          return
        }
        ctx.moveTo(x + radius, y)
        ctx.arcTo(x + width, y, x + width, y + height, radius)
        ctx.arcTo(x + width, y + height, x, y + height, radius)
        ctx.arcTo(x, y + height, x, y, radius)
        ctx.arcTo(x, y, x + radius, y, radius)
      },
      drawRoundedRect(ctx, strokeStyle, fillStyle, x, y, width, height, radius) {
        ctx.beginPath()
        this.roundedRect(ctx, x, y, width, height, radius)
        ctx.strokeStyle = strokeStyle
        ctx.fillStyle = fillStyle
        ctx.stroke()
        ctx.fill()
      },
      changeActive(index, id, price) {
        this.activeNum = index
        this.skuid = id
        this.price = price
      },
      commitOrder() {
        uni.setStorageSync('orderFrom', url.getCurrentPageUrl())
        uni.setStorageSync('order', [
          {
            skuId: this.skuid || this.goods.skuList[0].id,
            price: this.price,
            count: this.num,
            id: this.params.id
          }
        ])
        wx.navigateTo({
          url: `/pages/confirmOrder/index`
        })
      },
      add() {
        let sku = ''
        this.goods.skuList.map(item => {
          if (item.id === (this.skuid || this.goods.skuList[0].id)) {
            sku = item
          }
          return ''
        })
        shoppingCar
          .add({
            number: this.num,
            product: {
              ...this.goods
            },
            productId: this.params.id,
            skuId: this.skuid || this.goods.skuList[0].id,
            sku,
            userId: uni.getStorageSync('userId')
          })
          .then(data => {
            wx.showToast({
              title: '添加成功',
              duration: 2000
            })
          })
      }
    }
  }
</script>

<style>
  page {
    /* background: #eeded8; */
  }
</style>
<style lang="scss" scoped>
  .overflow {
    height: 100vh !important;
    overflow: hidden !important;
  }
  .line {
    text-decoration: line-through !important;
  }
  .j {
    font-size: 24rpx !important;
    color: #ccc !important;
    font-weight: 400 !important;
    margin-left: 10rpx !important;
  }
  .shadow {
    height: 100vh;
    width: 100vw;
    position: fixed;
    top: 0;
    height: 0;
    background-color: rgba(0, 0, 0, 0.4);
    z-index: 11111;
  }
  button {
    background-color: transparent;
    border: none;
    display: flex;
    flex-flow: column;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    &::after {
      display: none;
    }
  }
  .close {
    position: absolute;
    right: 0;
  }
  .quxiao {
    height: 100rpx;
    line-height: 80rpx;
    text-align: center;
    color: #363636;
    font-size: 32rpx;
  }
  .share {
    padding: 40rpx 60rpx;
    view {
      text-align: center;
    }
    image {
      width: 90rpx;
      height: 90rpx;
    }
  }
  .fanhuiIcon {
    width: 25px;
    height: 25px;
  }
  .demo {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #ff6a21;
    font-size: 31rpx;
    color: #fff;
    .left {
      float: left;
      position: absolute;
      width: max-content;
      height: max-content;
      top: 0;
      bottom: 0;
      left: 20rpx;
      margin: auto;
      .iconfont {
        color: #fff;
      }
    }
  }
  .nav {
    background: #ff6a21;
    color: #fff;
    padding-bottom: 5px;
    height: var(--status-bar-height);
    position: relative;

    image {
      width: 25px;
      height: 25px;
      position: absolute;
      bottom: 10px;
      left: 5px;
    }
  }
  .canvasBox {
    background-color: #fff;
    top: 160rpx;
    border-radius: 10px;
    overflow: hidden;
    position: fixed;
    z-index: 1075;
  }
  .canvas {
    position: fixed;
    top: 40rpx;
    left: 40rpx;
    z-index: 88888;
    width: 670rpx;
  }
  .qian {
    font-size: 21rpx;
    margin-top: 8rpx;
  }
  .fenxiaozi {
    font-size: 28rpx;
  }

  .fenxiao {
    background: #00b486;
    box-shadow: 0px 15px 50px 0px rgba(0, 180, 134, 0.4);
    color: #fff;
    width: 228rpx;
    height: 80rpx;
    border-radius: 80px;
    text-align: center;
  }
  .fenText {
    background: #fff0e8;
    height: 76rpx;
    text-align: center;
    color: #ff6a21;
    line-height: 76rpx;
    border-radius: 80px;
    font-size: 22rpx;
  }
  .right30 {
    width: 40rpx;
    height: 36rpx;
    right: 30rpx;
  }
  .top30 {
    top: 30rpx;
  }
  .mb90 {
    margin-bottom: 150rpx;
  }
  .navright {
    padding-bottom: 14rpx;
    image {
      width: 40rpx;
      height: 36rpx;
      margin-right: 45rpx;
    }
  }

  u-card {
    /deep/.u-card {
      box-sizing: border-box;
      margin: 0 !important;
      border-radius: 0 !important;
    }
  }
  .swiperBox /deep/ .u-swiper-wrap {
    border-radius: 0 !important;
  }
  .swiperBox /deep/ .u-list-image-wrap {
    border-radius: 0 !important;
  }
  .buttonBox {
    width: 100%;
    position: fixed;
    bottom: 60rpx;
    display: flex;
    justify-content: space-around;
    align-items: center;
  }
  .specification {
    flex-flow: row wrap;
  }
  .c-color-000 {
    font-size: 33rpx;
    font-weight: 600;
  }
  .c-color {
    color: #000;
  }
  .money {
    font-size: 32rpx;
    color: #ff6b22;
  }
  .swiperBox {
    // padding: 50rpx 30rpx 0;
  }
</style>

<style scoped>
  .a >>> swiper {
    height: 100vw !important;
  }
  .navBar >>> .u-navbar-inner {
    margin-right: 0 !important;
    align-items: flex-end !important;
  }
  u-cell-item >>> .u-cell {
    padding: 26rpx 0;
  }
  .c-fs0 {
    font-size: 0px;
  }
</style>
